import React, { useEffect, useRef, useState } from 'react';
import { Space, Table, Button, Modal } from 'antd';
import { Select,Popconfirm } from 'antd';
import { getuserlist, getuseradd, getroleList, getuserEdit, getuserdel } from '../../reques';
import { message, Form, Input } from 'antd';


const Index = () => {
    const [userlist, setUserlist] = useState([])
    const [form] = Form.useForm();
    let [title, setTitle] = useState('')
    //存入输入的账户名和下拉选择的管理信息
    const [roleData, setRoleData] = useState([])
    useEffect(() => {
        getuserlist().then(res => {
            // console.log(res)
            let { data: { code, msg, data } } = res
            if (code == 200) {
                setUserlist([...data].map(item => {
                    item.key = item.id
                    return item
                }))
            }
            //  console.log(userlist,99999)
        })

        // 角色列表数据
        getroleList().then(res => {
            // console.log(res, 'addlist')
            let roles = []
            res.data.data.forEach(item => {
                roles.push({
                    label: item.role,
                    value: item.id
                })
            })
            // console.log(roles, 'ag')
            setRoleData(roles)
            // console.log(roleData, 3434534)
        })


    }, [])




    const [isModalOpen, setIsModalOpen] = useState(false);
    const showModal = () => {
        setIsModalOpen(true);
    };

    const formRef = useRef(null)
    const onsubmit = () => {
        setIsModalOpen(false);
        // 获取表单内输入的内容
        formRef.current.submit()
    };
    const closeModal = () => {
        setIsModalOpen(false);
    };



    const add = () => {
        showModal()
        setTitle('添加')

    }

    // 页面没有Id 创建一个Id
    const [id, setId] = useState('')
    const edit = (e) => {
        // console.log(e,111)
        showModal()
        // 让创建的Id等于当前点击的Id
        setId(e.id)
        setTitle('修改')
        // console.log(e)
        // 回显
        form.setFieldsValue({
            username: e.username,
            password: e.password,
            roleId: e.roleId
        });

    }
    //  console.log(id,66)
    // 添加 编辑
    const onFinish = (values) => {
        console.log('Success:', values);
        if (title == '添加') {
            let { username, password, roleId } = values
            // console.log(values);
            getuseradd(
                {
                    username,
                    password,
                    roleId
                }
            ).then(res => {
                let { data: { msg, code } } = res
                if (code === 200) {
                    message.success(msg, 1.5)
                    // 在页面添加（不用重新刷新）
                    setUserlist([...userlist, {
                        username,
                        password,
                        rolename: roleData.find(item => item.value === roleId).label,
                        id: +new Date
                    }])
                    closeModal()
                    form.resetFields();
                }
            }
            )
        } else if (title == '修改') {
            values.id = id
            getuserEdit(values).then(res => {
                // console.log(res)
                setUserlist([...userlist])
            })
        }

    };

    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };


    // const del = (id) => {
    //     // console.log(id)
    //     getuserdel(id).then(res => {
    //         // console.log(res,"del")
    //     })
    // }
    const del = (e) => {
  console.log(e);
  getuserdel(e).then(res => {
            // console.log(res,"del")
            let {data:{code,msg}}=res
            if(code==200){
                let index=userlist.findIndex(item=>item.id==e)
                userlist.splice(index,1)
                setUserlist([...userlist])
                 message.success(msg,1.5);
            }else{
                message.error('删除失败',1.5);
            }
        })
 
};
const cancel = (e) => {
  console.log(e);
  message.error('Click on No');
};


    const columns = [
        {
            title: '编号',
            dataIndex: 'id',
            key: 'key',
            render: (text) => <a>{text}</a>,
        },
        {
            title: '用户',
            dataIndex: 'username',
            key: 'username',
        },
        {
            title: '身份',
            dataIndex: 'rolename',
            key: 'rolename',
        },

        {
            title: 'Action',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <a onClick={() => edit(record)}>编辑 </a>
                    <Popconfirm
                        title="确认删除？"
                        description="您确认删除？"
                        onConfirm={() => del(record.key)}
                        onCancel={cancel}
                        okText="Yes"
                        cancelText="No"
                    >
                        <a>删除</a>
                    </Popconfirm>
                </Space>
            ),
        },
    ];

    return (
        <div>
            <Button type="primary" onClick={add}>添加</Button>
            <Table columns={columns} dataSource={userlist} />
            <Modal title={title} open={isModalOpen} onOk={onsubmit} onCancel={closeModal}>
                <Form
                    form={form}
                    ref={formRef}
                    name="basic"
                    labelCol={{
                        span: 8,
                    }}
                    wrapperCol={{
                        span: 16,
                    }}
                    style={{
                        maxWidth: 600,
                    }}
                    initialValues={{
                        remember: true,
                    }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                >
                    <Form.Item
                        label="账号"
                        name="username"
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="密码"
                        name="password"
                    >
                        <Input />
                    </Form.Item>


                    <Form.Item
                        label="角色："
                        name="roleId"
                    >

                        <Select
                            style={{
                                width: 120,
                            }}

                            options={roleData}
                        />

                    </Form.Item>


                </Form>
            </Modal>


        </div>

    )
}
export default Index;
